package com.harvest.scientific.ladder.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;

import com.harvest.scientific.ladder.R;
import com.harvest.scientific.ladder.ext.CommonHelper;

import java.util.Objects;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;



public abstract class BaseDialog extends Dialog {

    private static final String TAG = BaseDialog.class.getSimpleName();
    private Activity mActivity;
    private boolean customDim;
    private float dimValue;

    public BaseDialog(@NonNull Context context) {
        this(context, R.style.dialogStyle);
    }

    public BaseDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        if (context instanceof Activity) {
            mActivity = (Activity) context;
        }
    }

    public BaseDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
        if (context instanceof Activity) {
            mActivity = (Activity) context;
        }
    }
    protected View rootView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (isActive()) {
            int layoutId = initLayout();
            if (layoutId > 0) {
                rootView = View.inflate(getContext(), layoutId, null);
                setContentView(rootView);
            }
            DisplayMetrics dm = new DisplayMetrics();
            WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
            windowManager.getDefaultDisplay().getMetrics(dm);
            WindowManager.LayoutParams lp = Objects.requireNonNull(getWindow()).getAttributes();
            lp.gravity = Gravity.CENTER;

            lp.width = (int) (getScreenWidth(getContext()) - 2 * dp2px(15f));
            lp.height = -2;
            if (customDim) {
                getWindow().setDimAmount(dimValue);  // 去掉遮罩层（全透明）
            }
            getWindow().setAttributes(lp);
            initView();
            initEvent();
        }
    }

    public void setWindowDimAmount(boolean customDim, float dimValue) {
        this.customDim = customDim;
        this.dimValue = dimValue;
    }

    //设置背景颜色
    protected Drawable getBackgroundDrawable() {
        return null;
    }

    protected int getSystemUiVisibility() {
        return View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    protected abstract int initLayout();

    protected abstract void initView();

    protected abstract void initEvent();

    /**
     * 设置dialog其他屏幕地方是否触摸消失
     *
     * @param isSetCanceledOnTouchOutside
     * @return
     */
    public BaseDialog setCanceledOnTouchOutside(Boolean isSetCanceledOnTouchOutside) {
        if (isActive()) {
            try {
                findViewById(android.R.id.content).setClickable(true);
                findViewById(android.R.id.content).setOnClickListener(v -> {
                    if (isSetCanceledOnTouchOutside) {
                        dismissDialog();
                    }
                });
                super.setCanceledOnTouchOutside(isSetCanceledOnTouchOutside);
            } catch (Exception e) {
                Log.d(TAG, "setCanceledOnTouchOutside: e : " + e.toString());
            }
        }
        return this;
    }

    /**
     * 设置回退键是否有效
     *
     * @param isCancelable
     * @return
     */
    public BaseDialog setCancelable(Boolean isCancelable) {
        if (isActive()) {
            try {
                findViewById(android.R.id.content).setClickable(true);
                findViewById(android.R.id.content).setOnClickListener(v -> {
                    if (isCancelable) {
                        dismissDialog();
                    }
                });
                super.setCancelable(isCancelable);
            } catch (Exception e) {
                Log.d(TAG, "setCancelable: e : " + e.toString());
            }
        }
        return this;
    }

    /**
     * 显示dialog
     *
     * @return
     */
    public BaseDialog showDialog() {
        if (isActive() && !isShowing()) {
            try {
                super.show();
                Log.d(TAG, "showDialog: show finish");
            } catch (Exception e) {
                Log.d(TAG, "showDialog: e : " + e.toString());
            }
        } else {
            Log.d(TAG, "showDialog: not isActive or isShowing");
        }
        return this;
    }

    /**
     * 关闭dialog
     *
     * @return
     */
    public BaseDialog dismissDialog() {
        if (isActive() && isShowing()) {
            try {
                super.dismiss();
                Log.d(TAG, "dismissDialog: dismiss finish");
            } catch (Exception e) {
                Log.d(TAG, "dismissDialog: e : " + e.toString());
            }
        } else {
            Log.d(TAG, "dismissDialog: not isActive or not isShowing");
        }
        return this;
    }

    /**
     * 当前Activity是否存在
     *
     * @return
     */
    public boolean isActive() {
        return mActivity != null && !mActivity.isFinishing();
    }

    public Activity getActivity() {
        return mActivity;
    }

    /**
     * 获取屏幕宽度
     *
     * @param context
     * @return
     */
    public int getScreenWidth(Context context) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        return displayMetrics.widthPixels;
    }

    /**
     * 获取屏幕高
     *
     * @param context
     * @return
     */
    public int getScreenHeight(Context context) {
        DisplayMetrics displayMetrics = CommonHelper.getDisplayMetrics();
        return displayMetrics.heightPixels;
    }

    /**
     * UI设计逻辑宽度
     */
    public static final float DESIGN_WIDTH = 375;

    public float dp2px(float dpValue) {
        final float scale = CommonHelper.getDisplayMetrics().widthPixels / DESIGN_WIDTH;
        return dpValue * scale;
    }
}

